//
//  TL_BindPhoneViewController.m
//  WXReader
//
//  Created by Andrew on 2018/7/27.
//  Copyright © 2018年 Andrew. All rights reserved.
//

#import "TL_BindPhoneViewController.h"

#import "TL_SendCodeButton.h"
#import "UIView+LayoutCallback.h"
#import "NSObject+Observer.h"

@interface TL_BindPhoneViewController ()

@property (nonatomic, weak) UITextField *accountTextField;

@property (nonatomic, weak) UITextField *codeTextField;

@property (nonatomic, weak) TL_SendCodeButton *sendCodeButton;

@property (nonatomic, weak) UIButton *bindingButton;

@end

@implementation TL_BindPhoneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initialize];
    [self createSubviews];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self setStatusBarDefaultStyle];
}


#pragma mark - 初始化
- (void)initialize {
    [self setNavigationBarTitle:WXLocalizedString(@"绑定邮箱")];
    
    self.view.backgroundColor = kWhiteColor;
}


#pragma mark - UI
- (void)createSubviews {
    CGFloat width = SCREEN_WIDTH - 4 * kMargin;
    CGFloat height = kGeometricWidth(width, 61.0, 334.0);
  
    UITextField *accountTextField = ({
        UITextField *accountTextField = [[UITextField alloc] init];
        self.accountTextField = accountTextField;
        accountTextField.backgroundColor = kWhiteColor;
        accountTextField.font = SYSTEM_FONT(16);
        accountTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        accountTextField.textColor = kBlackColor;
        [accountTextField addTarget:self action:@selector(textDidChange:) forControlEvents:UIControlEventEditingChanged];
        accountTextField.placeholder = WXLocalizedString(@"邮箱");
        accountTextField.keyboardType = UIKeyboardTypeEmailAddress;
        accountTextField.frameBlock = ^(UIView * _Nonnull view) {
            [view addBorderLineWithBorderWidth:kCellLineHeight borderColor:kGrayLineColor cornerRadius:0 borderType:UIBorderSideTypeBottom];
        };
        accountTextField;
    });
    [self.view addSubview:accountTextField];
    [accountTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(2 * kMargin);
        make.top.equalTo(self.view).offset(PUB_NAVBAR_HEIGHT + kLineX(40.0));
        make.height.mas_equalTo(height);
        make.right.equalTo(self.view).offset(-2 * kMargin);
    }];
    
    NSString *maxText = [NSString stringWithFormat:@"(%@)%@", @"59", WXLocalizedString(@"秒后可重新发送")];
    CGFloat maxWidth = [TL_ViewHelper getDynamicWidthWithLabelFont:kMainFont labelHeight:height labelText:maxText maxWidth:SCREEN_WIDTH / 2.0 - 50.0];
    UIView *rightView = ({
        UIView *rightView = [[UIView alloc] init];
        TL_SendCodeButton *sendCodeButton = [[TL_SendCodeButton alloc] initWithFrame:CGRectZero identify:@"login_timer"];
        self.sendCodeButton = sendCodeButton;
        sendCodeButton.enabled = NO;
        [sendCodeButton.titleLabel setFont:kMainFont];
        sendCodeButton.titleLabel.textAlignment = NSTextAlignmentCenter;
        [sendCodeButton setTitleColor:kMainColor forState:UIControlStateNormal];
        [sendCodeButton setTitleColor:RGB(199, 199, 205) forState:UIControlStateDisabled];
        [sendCodeButton addTarget:self action:@selector(sendCodeEvent:) forControlEvents:UIControlEventTouchUpInside];
        [rightView addSubview:sendCodeButton];
        [sendCodeButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(rightView);
            make.height.mas_equalTo(sendCodeButton.intrinsicContentSize.height);
            make.width.mas_equalTo(maxWidth);
        }];
        
        UIView *lineView = [[UIView alloc] init];
        lineView.backgroundColor = kGrayLineColor;
        [rightView addSubview:lineView];
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(rightView);
            make.size.mas_equalTo(CGSizeMake(1.0, kMargin));
            make.centerY.equalTo(rightView);
        }];
        rightView;
    });
    [self.view addSubview:rightView];
    rightView.frameBlock = ^(UIView * _Nonnull view) {
        [view addBorderLineWithBorderWidth:1.0 borderColor:kGrayLineColor cornerRadius:0.0 borderType:UIBorderSideTypeBottom];
    };
    [rightView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.height.equalTo(accountTextField);
        make.top.equalTo(accountTextField.mas_bottom).offset(kMargin);
        make.width.mas_equalTo(maxWidth + kMargin);
    }];
        
    UITextField *codeTextField = ({
        UITextField *codeTextField = [[UITextField alloc] init];
        self.codeTextField = codeTextField;
        codeTextField.backgroundColor = accountTextField.backgroundColor;
        codeTextField.keyboardType = UIKeyboardTypeNumberPad;
        codeTextField.font = accountTextField.font;
        codeTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        codeTextField.textColor = accountTextField.textColor;
        codeTextField.placeholder = WXLocalizedString(@"验证码");
        [codeTextField addTarget:self action:@selector(textDidChange:) forControlEvents:UIControlEventEditingChanged];
        codeTextField.frameBlock = ^(UIView * _Nonnull view) {
            [view addBorderLineWithBorderWidth:kCellLineHeight borderColor:kGrayLineColor cornerRadius:0 borderType:UIBorderSideTypeBottom];
        };
        codeTextField;
    });
    [self.view addSubview:codeTextField];
    [codeTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(2 * kMargin);
        make.top.equalTo(rightView);
        make.height.equalTo(accountTextField);
        make.right.equalTo(rightView.mas_left);
    }];
    
    UIButton *bindingButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.bindingButton = bindingButton;
    bindingButton.titleLabel.font = SYSTEM_FONT(15);
    [bindingButton setTitleColor:kWhiteColor forState:UIControlStateNormal];
    [bindingButton setTitleColor:kGrayTextColor forState:UIControlStateDisabled];
    [bindingButton setTitle:WXLocalizedString(@"绑定") forState:UIControlStateNormal];
    bindingButton.backgroundColor = RGB(229, 230, 231);
    [bindingButton addObserver:KEY_PATH(bindingButton, enabled) complete:^(UIButton * _Nonnull obj, id  _Nullable oldVal, id  _Nullable newVal) {
        obj.backgroundColor = [newVal boolValue] ? kMainColor : RGB(229, 230, 231);
    }];
    bindingButton.enabled = NO;
    bindingButton.frameBlock = ^(UIButton * _Nonnull button) {
        button.layer.cornerRadius = (CGRectGetWidth(button.bounds) + CGRectGetHeight(button.bounds)) * 0.058;
    };
    [bindingButton addTarget:self action:@selector(bindPhone) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:bindingButton];
    [bindingButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(2 * kMargin);
        make.right.equalTo(self.view).offset(-2 * kMargin);
        make.top.equalTo(codeTextField.mas_bottom).offset(IS_IPHONE_4_OR_LESS || IS_IPHONE_5 ? 40 : 60);
        make.height.equalTo(bindingButton.mas_width).multipliedBy(44.0 / 334.0);
    }];
}


#pragma mark - Event
- (void)textDidChange:(UITextField *)textField {
    if (!self.sendCodeButton.countdownState) {
        self.sendCodeButton.enabled = (self.accountTextField.text.length > 0);
    }
    
    self.bindingButton.enabled = (self.accountTextField.text.length > 0 && self.codeTextField.text.length > 0);
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

#pragma mark - 网络请求
- (void)sendCodeEvent:(TL_SendCodeButton *)button {
    
    if (![self.accountTextField.text containsString:@"@"]) {
        [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:WXLocalizedString(@"邮箱格式不正确")];
        return;
    }
    
    NSDictionary *params = @{@"email" : self.accountTextField.text};
    
    button.enabled = NO;

    MK_WEAK_SELF
    
    [APIManager sendPostRequest:[APIURLManager sendEmailValidCode] parameters:params model:nil success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        
        if (success) {
            [button startTiming];
            [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeSuccess alertTitle:WXLocalizedString(@"验证码已发送")];
            [weakSelf.codeTextField becomeFirstResponder];
        } else {
            button.enabled = YES;
            [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:requestModel.msg];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        button.enabled = YES;
        [TL_TopAlertManager showAlertWithError:error defaultText:WXLocalizedString(@"发送失败")];
    }];
}

- (void)bindPhone {
    self.view.userInteractionEnabled = NO;

    NSDictionary *params;
    
    params = @{
        @"email" : self.accountTextField.text,
        @"verificationCode" : self.codeTextField.text
    };
    
    
    MK_WEAK_SELF
    
    [APIManager sendPostRequest:[APIURLManager Bind_Email] parameters:params model:nil success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        
        if (success) {
            [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeSuccess alertTitle:WXLocalizedString(@"绑定成功")];
            !weakSelf.completionBlock ?: weakSelf.completionBlock();
            [weakSelf.navigationController popViewControllerAnimated:YES];
        } else {
            [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:requestModel.message];
            weakSelf.view.userInteractionEnabled = YES;
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [TL_TopAlertManager showAlertWithError:error defaultText:nil];
        weakSelf.view.userInteractionEnabled = YES;
    }];
}

@end
